package com.example.moban.view.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;


import com.example.moban.R;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * @author yql
 * Time: 2018/4/26.
 */

public abstract class SimpleDialogFragment extends DialogFragment {

    protected String TAG = getClass().getSimpleName();

    private FrameLayout mContentViewWithFragment;
    public Activity mContext;
    private Unbinder unbinder;

    /**
     * 透明度
     */
    protected int alpha = 150;
    /**
     * 背景色
     */
    protected int backgroundColor = 0;

    /**
     * dismiss后监听
     */
    protected DialogTimeOverBack dialogTimeOverBack;

    /**
     * 是否关闭弹窗 关闭时间
     */
    protected boolean close = false;
    protected long timeOut = 2000;
    protected Handler handler = new Handler();

    private boolean cancelable = true;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = (Activity) context;
    }

    /**
     * 初始化屏幕属性
     */
    @Override
    public void onStart() {
        super.onStart();
        //设置圆角
        Rect displayRectangle = new Rect();
        Window window = getDialog().getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
        //此处可以设置dialog显示的位置
        window.setGravity(Gravity.CENTER);
//        window.setBackgroundDrawableResource(R.drawable.shape_white_radius30 );
        window.setBackgroundDrawableResource(R.drawable.shape_lucency );
        //设置背景透明度
        if (alpha == 0) {
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.dimAmount = 0.0f;
            window.setAttributes(layoutParams);
        }
        if (dialogTimeOverBack != null) {
            handler.postDelayed(runnable, timeOut);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //去掉默认标题栏  不然会出现界面留白(requestWindowFeature方法必须在setContentView加载布局之前调用。)
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialogCancel();

        View rootView = inflater.inflate(R.layout.dialog_base, container, false);
        if (mContentViewWithFragment == null) {
            mContentViewWithFragment = rootView.findViewById(com.rzhd.coursepatriarch.common.R.id.mContentViewWithFragment);
            setContentView(inflater, mContentViewWithFragment, savedInstanceState);
            //必须要放在初始化view后  使用view之前
            unbinder = ButterKnife.bind(this, rootView);
            initView(rootView);
            initData();
        }
        return rootView;
    }

    /**
     * 设置布局
     */
    public abstract void setContentView(@NonNull LayoutInflater inflater, FrameLayout contentView, Bundle savedInstanceState);

    /**
     * 初始化View
     */
    public abstract void initView(View view);

    /**
     * 初始化数据
     */
    public abstract void initData();


    private void dialogCancel(){
        getDialog().setCancelable(cancelable);
        getDialog().setCanceledOnTouchOutside(cancelable);
        if(cancelable){
            return;
        }
        getDialog().setOnKeyListener( new DialogInterface.OnKeyListener(){
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
//            dismiss();
                    return false;
                } else {
                    //这里注意当不是返回键时需将事件扩散，否则无法处理其他点击事件
                    return false;
                }
            }
        } );
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != unbinder) {
            unbinder.unbind();
        }
        Log.e(TAG, "onDestroyView");
    }

    @Override
    public void dismiss() {
        if (getActivity() == null || getActivity().isDestroyed() || getActivity().isFinishing()) {
            return;
        }
        super.dismiss();
        if (dialogTimeOverBack != null) {
            dialogTimeOverBack.TimeOver();
        }
    }

    public void setAlpha(int alpha) {
        this.alpha = alpha;
    }

    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
    }

    public void setDialogTimeOverBack(DialogTimeOverBack dialogTimeOverBack) {
        this.dialogTimeOverBack = dialogTimeOverBack;
    }

    public interface DialogTimeOverBack {
        void TimeOver();
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        //暂时解决 IllegalStateException: Can not perform this action after onSaveInstanceState
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        // 这里吧原来的commit()方法换成了commitAllowingStateLoss()
        ft.commitAllowingStateLoss();
    }

    protected Runnable runnable = new Runnable() {
        @Override
        public void run() {
            dismiss();
        }
    };

    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

    public void setClose(boolean close) {
        this.close = close;
    }

    public void setDialogCancelable(boolean cancelable) {
        this.cancelable = cancelable;
    }
}
